use cmd_arg_util::{CommandLineProcessor, ParameterType};
use std::sync::{Arc, RwLock};

#[derive(Debug)]
pub struct CmdArg {
    pub setting_server_addr: String, // 配置中心地址
    pub app_node: String,            // 本程序对应节点名
    pub local_ip: String,            // 本机Ip
}

lazy_static::lazy_static! {
    /// 命令行参数
    static ref CMD_ARG_OBJ: RwLock<Option<Arc<CmdArg>>> = RwLock::new(None);
}

/// 获取命令行的参数
pub fn get_cmd_arg() -> Arc<CmdArg> {
    CMD_ARG_OBJ.read().unwrap().as_ref().unwrap().clone()
}

pub(crate) fn parse() {
    println!("运行的命令行为:{:?}", std::env::args_os());

    let mut processor = CommandLineProcessor::new();

    let setting_param =
        processor.add_simple_parameter("setting", ParameterType::String, "setting server addr");
    let node_param = processor.add_simple_parameter("node", ParameterType::String, "app node path");
    let local_ip_param =
        processor.add_simple_parameter("localIp", ParameterType::String, "the local machine ip");
    processor.parse_command_line();

    let setting_addr = setting_param
        .to_string_value()
        .expect("setting value error");
    let node = node_param.to_string_value().expect("node value error");
    let local_ip = local_ip_param
        .to_string_value()
        .expect("localIp value error");
    if setting_addr.is_empty() {
        panic!("setting addr can not empty")
    }
    if node.is_empty() {
        panic!("node can not empty")
    }
    if local_ip.is_empty() {
        panic!("local ip can not empty")
    }

    *CMD_ARG_OBJ.write().unwrap() = Some(Arc::new(CmdArg {
        setting_server_addr: setting_addr,
        app_node: node,
        local_ip,
    }));
}
